package ru.susu.algebra.partition.polyhedron.checkers;

import java.util.BitSet;
import java.util.List;

import ru.susu.algebra.pair.Pair;
import ru.susu.algebra.partition.Partition;
import ru.susu.algebra.partition.polyhedron.VertexHelper;
import ru.susu.algebra.partition.vectex.Partition2VertexCache;

/**
 * @author akargapolov
 * @since: 11.03.2010
 */
public class TwoCompositionChecker implements IVertexChecker
{

	@Override
	public String check(Partition partition, List<Partition> allPartitions)
	{
		Pair<Integer, Integer>[] pairs = Partition2VertexCache.getPairs(partition);
		Integer number = partition.getPresentedNumber();
		for (int startIndex = 0;startIndex < pairs.length;startIndex++)
		{
			BitSet bitset = new BitSet(2 * number + 1);
			bitset.set(number);
			bitset = recalculate(bitset, pairs[startIndex].getKey(), pairs[startIndex].getValue(), false);
			for (int curIndex = startIndex + 1; curIndex < pairs.length; curIndex++)
				bitset = recalculate(bitset, pairs[curIndex].getKey(), pairs[curIndex].getValue(), true);
			if (bitset.get(number))
				return VertexHelper.getVertexString(partition);
		}
		return CHECKED_RESULT;
	}

	private BitSet recalculate(BitSet bitset, int number, int count, boolean bitsetsUnion)
	{
		BitSet result = (BitSet)bitset.clone();
		if (!bitsetsUnion)
			result.clear();

		for (int i = 0;i<bitset.length(); i++)
		{
			if (!bitset.get(i))
				continue;

			for (int j = 1;j<=count;j++)
			{
				result.set(i + number*j);
				result.set(i - number*j);
			}
		}

		return result;
	}

}
